package com.nwpu.hass.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.nwpu.hass.domain.AuthEntity;
import com.nwpu.hass.exceptions.AuthorizeException;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Map;

/**
 * @author alecHe
 * @desc 提供JWT的编码和解码
 * @date 2021-01-09 10:50:57
 */
public class JwtUtils {
    /**
     * 编码JWT
     * @param authEntity 存储在Redis中的payload
     * @param secret 密钥，由驱动层随机生成
     * @param timeout 过期时间,单位ms
     * @return token
     */
    public static String encodeJwt(AuthEntity authEntity,String secret,long timeout){
        Algorithm algorithm = Algorithm.HMAC256(secret);
        String token = JWT.create()
//                .withExpiresAt(new Date(System.currentTimeMillis() + timeout))
                .withClaim("userId",authEntity.getUserId())
                .withClaim("role",authEntity.getRole())
                .withClaim("clientCode",authEntity.getClientCode())
                .sign(algorithm);
        return token;
    }

    /**
     * 解码JWT
     * @param token JWT json web token
     * @param secret 密钥，存储在Redis中
     * @return 之前存储的payload信息
     */
    public static Map<String, Claim> decodeJwt(String token,String secret){
        if(StringUtils.isBlank(token)){
            throw new AuthorizeException("token为空 " + token);
        }
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT.getClaims();
    }
}
